package geektime.spring.hello.hellospring.dataSource;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.Resource;
import javax.sql.DataSource;
// 多数据源demo
@Slf4j
@Configuration
@EnableTransactionManagement
public class ManyDataSourceDemo {


    // foo 数据库
    @Bean
    @ConfigurationProperties("foo.datasource")
    public DataSourceProperties fooDataSourceProperties(){
        return new DataSourceProperties();
    }
    @Bean
    public DataSource fooDataSource(){
        DataSourceProperties fooProperties = fooDataSourceProperties();
        log.info(" fooDataUrl :{}",fooProperties.getUrl());
        return fooProperties.initializeDataSourceBuilder().build();
    }
    @Bean
    @Resource
    public PlatformTransactionManager fooTxManager(DataSource fooDataSource){
        return  new DataSourceTransactionManager(fooDataSource);
    }
    // foo 数据库结束


    // bar 数据库
    @Bean
    @ConfigurationProperties("bar.datasource")
    public DataSourceProperties barDataSourceProperties(){
        return new DataSourceProperties();
    }
    @Bean
    public DataSource barDataSource(){
        DataSourceProperties fooProperties = fooDataSourceProperties();
        log.info(" barDataUrl :{}",fooProperties.getUrl());
        return fooProperties.initializeDataSourceBuilder().build();
    }
    @Bean
    @Resource
    public PlatformTransactionManager barTxManager(DataSource fooDataSource){
        return  new DataSourceTransactionManager(fooDataSource);
    }
    // foo 数据库结束
}
